import algoliasearch from 'algoliasearch';

const client = algoliasearch('{{appId}}', '{{apiKey}}');
const index = client.initIndex('{{indexName}}');

const $searchBox = document.querySelector('#searchBox input[type=search]');
const $hits = document.querySelector('#hits');

function renderHits(query) {
  index.search(query).then(result => {
    // Please sanitize user-provided data when using `innerHTML` to avoid XSS
    $hits.innerHTML = `
      <ol class="ais-hits">
        ${result.hits
          .map(
            hit =>
              `<li class="ais-hits--item">
                <article>
                {{#if attributesToDisplay}}
                  {{#if imageAttribute}}
                  <img src="${ hit.{{imageAttribute}} }" alt="${ hit.{{attributesToDisplay.[0]}} }" />
                  {{/if}}
                  <div>
                    <h1>${hit._highlightResult.{{attributesToDisplay.[0]}}.value}</h1>
                    {{#each attributesToDisplay}}
                    {{#unless @first}}
                    <p>${hit._highlightResult.{{this}}.value}</p>
                    {{/unless}}
                    {{/each}}
                  </div>
                {{else}}
                  <p>
                    <code>${JSON.stringify(hit).slice(0, 100)}...</code>
                  </p>
                {{/if}}
                </article>
              </li>`
          )
          .join('')}
      </ol>`;
  });
}

$searchBox.addEventListener('input', event => {
  const query = event.target.value;

  renderHits(query);
});

renderHits('');
